<script setup lang="ts">
  import PartApply from './FormModal.vue'
  import CheckParts from './CheckParts.vue'
  import { PropType, ref } from 'vue'
  import { getOrderDetailWorkSpareList } from '@/api/parts'
  import PartsDetail from '@/views/order/parts/components/PartsDetail.vue'
  import { useUserStore } from '@/store/modules/user'
  import { TableColumnCtx } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { usePushDown } from '@/store/modules/pushDown'

  defineOptions({
    name: 'OrderDetailSparePartList',
  })

  const { setOrderPushDownInfo } = usePushDown()

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'updated'): void
  }>()

  // 全局路由对象
  const router = useRouter()

  /**
   * 申请类型
   * spare-part - 配件
   * backup-machine - 备用机
   */
  const applyType = ref<'spare-part' | 'backup-machine'>('spare-part')

  // 配件申请弹窗显示状态
  const sparePartModalVisible = ref(false)

  // 客户状态管理
  const userStore = useUserStore()

  // 分页配置
  const pagination = ref({
    limit: 100,
    page: 1,
  })

  // 配件列表
  const tableData = ref<Array<OrderDetailAPIResponse.SparePartListItem>>([])

  // 表格总条数
  const total = ref(0)

  // 配件
  const getOrderWorkSpareList = async () => {
    const res = await getOrderDetailWorkSpareList(pagination.value, props.orderDetail.id)
    tableData.value = res.data.data.rows
    total.value = Number(res.data.data.total)
  }

  // 配件id
  const partsId = ref('')

  // 配件审核弹窗状态
  const checkPartsModalVisible = ref(false)

  // 配件审核事件
  const handlePartCheck = (sparePart: OrderDetailAPIResponse.SparePartListItem) => {
    partsId.value = sparePart.id
    applyType.value = sparePart.isStandby === 1 ? 'backup-machine' : 'spare-part'
    checkPartsModalVisible.value = true
  }

  /**
   * 配件编辑点击事件
   * @param sparePart - 配件对象
   */
  const handleSparePartEditClick = (sparePart: OrderDetailAPIResponse.SparePartListItem) => {
    partsId.value = sparePart.id
    applyType.value = sparePart.isStandby === 1 ? 'backup-machine' : 'spare-part'
    sparePartModalVisible.value = true
  }

  // 配件详情弹窗状态
  const partsDetailModalVisible = ref(false)

  // 查看费用详细
  const handleViewPartsDetail = (n: string) => {
    partsDetailModalVisible.value = true
    partsId.value = n
  }

  /**
   * 列表更新事件
   */
  const onUpdateTableData = () => {
    getOrderWorkSpareList()
    emits('updated')
  }

  // 合计
  const getSummaries = (param: {
    columns: TableColumnCtx<OrderDetailAPIResponse.SparePartListItem>[]
    data: Array<OrderDetailAPIResponse.SparePartListItem>
  }) => {
    const arr = ['qty', 'priceTotal', 'customerUndertakePriceTotal', 'networkUndertakePriceTotal']
    const { columns, data } = param

    const sums: string[] = []
    columns.forEach((column, index) => {
      if (index == 0) {
        sums[index] = '合计'
        return
      }
      if (!arr.includes(column.property)) {
        return
      }
      const values = data.map((item) => Number(column.property in item ? column.property : ''))

      if (!values.every((value) => Number.isNaN(value))) {
        const valuesTotal = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        sums[index] = `${column.property == 'qty' ? '' : '￥'}${
          column.property == 'qty' ? valuesTotal : valuesTotal.toFixed(2)
        }`
      } else {
        sums[index] = ''
      }
    })
    return sums
  }

  /**
   * 申请配件和申请备用机点击事件
   * @param _applyType - 申请类型：spare-part(配件)、backup-machine(备用机)
   */
  const handleShowSparePartModal = (_applyType: typeof applyType.value) => {
    partsId.value = ''
    applyType.value = _applyType
    sparePartModalVisible.value = true
  }

  /**
   * 返厂单号点击事件
   * @param returnFactoryId - 返厂单id
   */
  const handleReturnFactoryNoClick = (returnFactoryId: string) => {
    router.push({ path: `/return/factory/detail/${returnFactoryId}` })
  }

  /**
   * 备用机点击事件
   * @param sparePart - 备用机对象
   */
  const handlePushDownReturnFactoryClick = (
    sparePart: OrderDetailAPIResponse.SparePartListItem,
  ) => {
    setOrderPushDownInfo(
      {
        address: '',
        area: '',
        buyMarket: '',
        buyTime: sparePart.warrantyStartTime || '',
        city: '',
        codes: [
          {
            activa: false,
            activaTime: '',
            archived: false,
            batchGoodsId: '',
            batchId: '',
            blacklist: false,
            buyMarket: '',
            codeSource: 1,
            createEmp: '',
            createEmpId: '',
            custAccId: '',
            dateOfProduction: '',
            disabled: false,
            gmtCreate: '',
            gmtUpdate: '',
            goodsId: '',
            goodsSpecId: '',
            id: '',
            lotNo: '',
            network: '',
            networkId: '',
            outStoreActiva: false,
            outStoreWarranty: false,
            outboundStoreNumber: '',
            produceDate: '',
            registerCode: null,
            remainingWarrantyDay: 0,
            remark: '',
            saleModels: '',
            saleNetworkName: '',
            saleNetworkNumber: '',
            salePrice: '',
            securityCode: sparePart.snCodes && sparePart.snCodes.length ? sparePart.snCodes[0] : '',
            sendGoodsNumber: '',
            status: 1,
            storeCode: '',
            storeId: '',
            storePositionId: '',
            storeStatus: 1,
            type: 1,
            updateEmp: '',
            updateEmpId: '',
            warrantyDay: 0,
            warrantyEndTime: '',
            warrantyStartTime: '',
            workOrderCode: null,
          },
        ],
        endTime: sparePart.warrantyEndTime || '',
        goodsBrand: sparePart.goodsBrand,
        goodsBrandId: sparePart.goodsBrandId,
        goodsCode: sparePart.goodsCode || '',
        goodsId: sparePart.goodsId,
        goodsModel: sparePart.goodsModel || '',
        goodsName: sparePart.goodsName || '',
        goodsSpec: sparePart.goodsSpec || '',
        goodsSpecId: sparePart.goodsSpecId,
        goodsType: sparePart.goodsType,
        id: sparePart.id,
        province: '',
        qty: sparePart.qty || 1,
        saleModels: null,
        town: '',
        userId: '',
        userName: '',
        userPhone: '',
        workGoodsAnnexVos: [],
        repairId: null,
        repairNo: null,
        dl: '',
        specialBz: '',
        standard: '',
        voltage: '',
        xlh: '',
        isStandby: sparePart.isStandby,
      },
      props.orderDetail,
    )
    router.push({ path: '/return/factory/new' })
  }

  defineExpose({
    getList: getOrderWorkSpareList,
    getSparePartList: tableData,
  })
</script>

<template>
  <div class="order-spare-part-list">
    <div class="title">
      <h-plain-button
        v-if="props.orderDetail.status === 3"
        :padding-lr="6"
        :height="22"
        @click="handleShowSparePartModal('spare-part')"
      >
        申请配件
      </h-plain-button>
      <h-plain-button
        v-if="props.orderDetail.status === 3"
        :padding-lr="6"
        :height="22"
        @click="handleShowSparePartModal('backup-machine')"
      >
        申请备用机
      </h-plain-button>
    </div>

    <el-table
      resizable
      :data="tableData"
      stripe
      style="width: 100%"
      :max-height="300"
      :border="true"
      show-summary
      :summary-method="(val) => getSummaries(val)"
    >
      <!-- 序号 -->
      <el-table-column type="index" label="序号" fixed="left" width="50" :align="'center'" />

      <!-- 配件单号 -->
      <el-table-column show-overflow-tooltip fixed="left" prop="code" label="配件单号" width="140">
        <template #default="{ row }">
          <span class="number" @click="handleViewPartsDetail(row.id)">
            {{ row.code }}
          </span>
        </template>
      </el-table-column>

      <!-- 出库单号 -->
      <el-table-column prop="storeOutboundCode" label="出库单号" width="160" />

      <!-- 申请类型 -->
      <el-table-column prop="type" label="申请类型" width="100" />

      <!-- 是否为备用机 -->
      <el-table-column prop="isStandby" label="是否为备用机" width="100">
        <template #default="{ row }">
          {{ row.isStandby == 1 ? '是' : '否' }}
        </template>
      </el-table-column>

      <!-- 配件名称 -->
      <el-table-column show-overflow-tooltip prop="model" label="配件名称" width="200" />

      <!-- 合格证 -->
      <el-table-column show-overflow-tooltip prop="model" label="合格证" width="140">
        <template #default="{ row }">
          {{ (row.snCodes || []).join('、') }}
        </template>
      </el-table-column>

      <!-- 旧件处理方式 -->
      <el-table-column show-overflow-tooltip label="旧件处理方式" width="100">
        <template #default="{ row }">
          {{ row.oldCopeWay == 1 ? '废弃' : row.oldCopeWay == 2 ? '旧件退回' : '' }}
        </template>
      </el-table-column>

      <!-- 申请人员 -->
      <el-table-column show-overflow-tooltip prop="applyEmp" label="申请人员" width="120" />

      <!-- 申请时间 -->
      <el-table-column show-overflow-tooltip prop="createTime" label="申请时间" width="128" />

      <!-- 数量 -->
      <el-table-column show-overflow-tooltip prop="number" label="数量" width="50" />

      <!-- 公司承担单价 -->
      <el-table-column
        v-if="!userStore.isCurrentRoleNetwork"
        show-overflow-tooltip
        prop="price"
        label="公司承担单价"
        width="150"
      >
        <template #default="{ row }">
          {{ row.isStandby === 0 ? `￥${(row.price || 0).toFixed(2)}` : '' }}
        </template>
      </el-table-column>

      <!-- 收取客户单价 -->
      <el-table-column
        v-if="!userStore.isCurrentRoleNetwork"
        show-overflow-tooltip
        prop="customerUndertakePrice"
        label="收取客户单价"
        width="150"
      >
        <template #default="{ row }">
          {{ row.isStandby === 0 ? `￥${(row.customerUndertakePrice || 0).toFixed(2)}` : '' }}
        </template>
      </el-table-column>

      <!-- 支付部门单价 -->
      <el-table-column
        show-overflow-tooltip
        prop="networkUndertakePrice"
        label="支付部门单价"
        width="150"
      >
        <template #default="{ row }">
          {{ row.isStandby === 0 ? `￥${(row.networkUndertakePrice || 0).toFixed(2)}` : '' }}
        </template>
      </el-table-column>

      <!-- 公司承担总费用 -->
      <el-table-column
        v-if="!userStore.isCurrentRoleNetwork"
        show-overflow-tooltip
        prop="priceTotal"
        label="公司承担总费用"
        width="150"
      >
        <template #default="{ row }">
          {{ row.isStandby === 0 ? `￥${(row.priceTotal || 0).toFixed(2)}` : '' }}
        </template>
      </el-table-column>

      <!-- 收取客户总费用 -->
      <el-table-column
        v-if="!userStore.isCurrentRoleNetwork"
        show-overflow-tooltip
        prop="customerUndertakePriceTotal"
        label="收取客户总费用"
        width="150"
      >
        <template #default="{ row }">
          {{ row.isStandby === 0 ? `￥${(row.customerUndertakePriceTotal || 0).toFixed(2)}` : '' }}
        </template>
      </el-table-column>

      <!-- 支付部门总费用 -->
      <el-table-column
        show-overflow-tooltip
        prop="networkUndertakePriceTotal"
        label="支付部门总费用"
        width="150"
      >
        <template #default="{ row }">
          {{ row.isStandby === 0 ? `￥${(row.networkUndertakePriceTotal || 0).toFixed(2)}` : '' }}
        </template>
      </el-table-column>

      <!-- 审核人员 -->
      <el-table-column show-overflow-tooltip prop="reviewEmp" label="审核人员" width="120" />

      <!-- 审批时间 -->
      <el-table-column show-overflow-tooltip prop="reviewTime" label="审批时间" width="128" />

      <!-- 返厂单号 -->
      <el-table-column label="返厂单号" width="140">
        <template #default="{ row }">
          <h-link @click="handleReturnFactoryNoClick(row.repairId)">{{ row.repairNo }}</h-link>
        </template>
      </el-table-column>

      <!-- 状态 -->
      <el-table-column prop="state" label="状态" width="83" fixed="right" :align="'center'">
        <template #default="{ row }">
          <div class="flex_justify_center">
            <h-status v-if="row.status === 1" type="warning">待审核</h-status>
            <h-status v-if="row.status === 2" type="success">已通过</h-status>
            <h-status v-if="row.status === 3" type="error">已驳回</h-status>
            <h-status v-if="row.status === 4" type="info">已撒回</h-status>
            <h-status v-if="row.status === 5" type="info">已取消</h-status>
          </div>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <h-space>
            <div v-permission="'order_review_product'" class="ord_dis">
              <h-link v-if="row.status == 1" @click="handlePartCheck(row)">审核</h-link>
              <h-link v-else disabled type="info">审核</h-link>
            </div>
            <h-link v-if="row.status === 3" @click="handleSparePartEditClick(row)">编辑</h-link>
            <h-link v-else disabled type="info">编辑</h-link>
            <template v-if="row.status === 2">
              <h-link
                v-if="row.isRelationRepair === 0"
                @click="handlePushDownReturnFactoryClick(row)"
              >
                下推返厂单
              </h-link>
              <h-link v-else disabled>已下推返厂单</h-link>
            </template>
          </h-space>
        </template>
      </el-table-column>
    </el-table>

    <!-- 审核/编辑配件 -->
    <check-parts
      v-model="checkPartsModalVisible"
      :work-id="props.orderDetail.id"
      :parts-id="partsId"
      :apply-type="applyType"
      :network-id="props.orderDetail.networkId"
      @update-list="onUpdateTableData"
    />

    <!-- 查看详细弹出框 -->
    <parts-detail v-model="partsDetailModalVisible" :parts-id="partsId" />

    <part-apply
      v-model="sparePartModalVisible"
      :order-detail="props.orderDetail"
      :spare-part-id="partsId"
      :apply-type="applyType"
      @update-list="onUpdateTableData"
    />
  </div>
</template>

<style scoped lang="scss">
  .order-spare-part-list {
    display: flex;
    flex-direction: column;
    background-color: #fff;
    padding: 12px;
    box-sizing: border-box;
    row-gap: 8px;

    .title {
      display: flex;
      align-items: center;
      column-gap: 4px;
    }

    .footer {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
